package com.felix.collection.sync;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Memoizer
 *
 * @author xjh
 * @version 1.0
 * @date 2019-03-28
 */
public class Memoizer<A, V> implements Computable<A, V> {

    private final Map<A, V> cache = new ConcurrentHashMap<>();
    private final Computable<A, V> c;

    public Memoizer(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V computable(A arg) throws InterruptedException {
        V result = cache.get(arg);
        if (result == null) {
            result = c.computable(arg);
            cache.put(arg, result);
        }
        return result;
    }
}
